package com.hutiao.snowhb.common;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;

public class SimsimiClient implements java.io.Serializable {
	
	private static final long serialVersionUID = 6224772011873590065L;

	static Logger logger = Logger.getLogger(SimsimiClient.class);
	
	//private static final String URL = "http://sandbox.api.simsimi.com/request.p?lc=ch&ft=1.0";
	
	private static final String KEY = "c17d36d3-4637-4e0c-88db-b7188a28e558";
	
	private static int retryCount = 3;
	
	private static int retryIntervalMillis = 500;
	
	private static int connectionTimeout = 5000;
	
	private static int soTimeout = 5000;

	private static final String URL = "http://sandbox.api.simsimi.com/request.p?key=c17d36d3-4637-4e0c-88db-b7188a28e558&lc=ch&ft=1.0";//&text=%E8%82%9A%E5%AD%90%E9%A5%BF%E4%BA%86
	
	public static String chat(String message) throws UnsupportedEncodingException {
		
		message = URLEncoder.encode(message, "UTF-8");
		
		MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        //connectionManager.closeIdleConnections(100);
        connectionManager.getParams().setConnectionTimeout(connectionTimeout);
        connectionManager.getParams().setSoTimeout(soTimeout);
        HttpClient httpclient = new HttpClient(connectionManager);
		GetMethod get = new GetMethod(URL+"&text="+message);
		
		int responseCode;
		String res;
		String ret = "";
		
		int retriedCount = 1;
		try {
			for (retriedCount = 1; retriedCount <= retryCount; retriedCount++) {
				
				responseCode = httpclient.executeMethod(get);
				res = get.getResponseBodyAsString();

				if (responseCode == 200) {
					
					JSONObject jsonObject = JSONObject.fromObject(res);
					
					Map<String, Class<?>> clazzMap = new HashMap<String, Class<?>>();
			        clazzMap.put("result", String.class);
			        clazzMap.put("response", String.class);
			        clazzMap.put("id", String.class);
			        clazzMap.put("msg", String.class);
			        Map<String, ?> mapBean = (Map) JSONObject.toBean(jsonObject, Map.class, clazzMap);
			        ret = mapBean.get("response").toString();
			        //System.out.println(mapBean);
			        
			        Set<String> set = mapBean.keySet();
			        Iterator<String> iter = set.iterator();
			        while (iter.hasNext()) {
			            String key = iter.next();
			            //fail(key + ":" + mapBean.get(key).toString());
			            logger.debug(key + ":" + mapBean.get(key).toString());
			        }
					
					break;
				}
				
				try {
					logger.debug(res);
					logger.info("Sleeping " + retryIntervalMillis + " millisecs for next retry.");
					Thread.sleep(retryIntervalMillis);
				} catch (InterruptedException ignore) {
					// nothing to do
				}
			}

		} catch (HttpException e) {
			logger.error("simsimi error:"+e.getMessage());
		} catch (IOException ioe) {
			logger.error("simsimi error:"+ioe.getMessage());
		} finally {
			get.releaseConnection();
			get = null;
		}
		
		return ret;
		
	}
	
	
	
}
